package com.yulang.security.core.config;

import com.alibaba.fastjson.JSONObject;
import com.yulang.security.BaseResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.session.InvalidSessionStrategy;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyInvalidSessionStrategy implements InvalidSessionStrategy {

    private SessionRegistry sessionRegistry;

    public MyInvalidSessionStrategy(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BaseResult baseResult = BaseResult.error(HttpStatus.UNAUTHORIZED.value(),"认证过期");
        cancelCookie(request,response);
        //sessionRegistry.removeSessionInformation(request.getSession().getId());
        sessionRegistry.removeSessionInformation(request.getRequestedSessionId());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(baseResult));
        response.getWriter().flush();

    }

    /**
     * Sets a "cancel cookie" (with maxAge = 0) on the response to disable persistent
     * logins.
     */
    protected void cancelCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("JSESSIONID", null);
        cookie.setMaxAge(0);
        cookie.setPath(getCookiePath(request));
        response.addCookie(cookie);
    }

    private String getCookiePath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return contextPath.length() > 0 ? contextPath : "/";
    }

}
